package ar.com.profertil.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * The Class XMLToString.
 */
public class XMLToString {

    /**
     * Instantiates a new xML to string.
     */
    public XMLToString() {
    }

    /**
     * Execute.
     * SOLO FUNCIONA PARA JAVA 1.5
     * @param in the in
     * @param out the out
     */
    public void execute(InputStream in, OutputStream out) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transform = tf.newTransformer();
            Document docout = db.newDocument();
            Element root = docout.createElement("ns1:BAPI_AR_WS_EXP_REJ_RESP_2758.Response");
            root.setAttribute("xmlns:ns1", "urn:sap-com:document:sap:rfc:functions");
            docout.appendChild(root);
            Element stringinp = docout.createElement("XML_DATA");
            root.appendChild(stringinp);
            BufferedReader inpxml = new BufferedReader(new InputStreamReader(in));
            StringBuffer buffer = new StringBuffer();
            String line = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
            buffer.append(line + "\n");
            while((line = inpxml.readLine()) != null) {
            	buffer.append(line + "\n");
            }
            String inptxml = buffer.toString();
            org.w3c.dom.Text srcxml = docout.createTextNode(inptxml);
            stringinp.appendChild(srcxml);
            DOMSource domS = new DOMSource(docout);
            transform.transform(domS, new StreamResult(out));
        } catch(Exception e) {
        	e.printStackTrace();
        }
    }
}